#coding=utf-8
from sqlalchemy.exceptions import InvalidRequestError
from stockdb.misc import *
from moneyflow import *
'''
使用示例:
from stockdb.misc import *
s = find_stock('600754')
print s.name
td = s.latest_td

import moneyflow.analyse as ma
a = ma.Analyst1(td)
r = a.stats()
大于20000的
r = a.stats(200000)
r
'''

def get_dealstats(td, threshold, direction):
    try:
        return sess.query(DealStats).filter_by(td=td, threshold=threshold, direction=direction).one()
    except InvalidRequestError:
        return None
        
def set_dealstats(td, threshold, direction, result_dict):
    r = result_dict
     
    ds = DealStats()

    ds.td = td
    ds.threshold = threshold
    ds.direction = direction
    
    ds.buy_num, ds.buy_money = r['b']
    ds.sell_num, ds.sell_money = r['s']
    ds.neutral_num, ds.neutral_money = r['n']
    ds.bs_num, ds.bs_money = r['b-s']
 
    sess.save(ds)
    sess.commit()
           
class Analyst1(object):
    
    def __init__(self, td):
        self.td = td
        
        self.code = td.fins.code
        self.date = td.date.isoformat()
    
    def has_deals(self):
        if self.td.deals:return True
        return False
    
    def deals2db(self):
        if not deal_exists(self.code, self.date):
            download2csv(self.code, self.date)
    
        ds = csv2deal(self.code, self.date)

        for d in ds:
            d2 = Deal2()
            
            d2.td = self.td; d2.time = d.time; 
            d2.price = d.price; d2.volume = d.volume; 
            d2.amount = d.price * d.volume 
            d2.bors = d.bors
            
            sess.save(d2)

        sess.commit()
        
    def stats(self, threshold=0, direction='>'):
    
        '''
        统计结果:
        {'b':[比数,总金额],'s':...,'n':..., 'b-s':买卖盘差额}
        '''
        
        def count(deals):   
            s = sum([d.amount for d in deals])
            return [len(deals), s]
            
        if not self.has_deals():
            self.deals2db()
        
        ds = get_dealstats(self.td, threshold, direction)
        if ds:
            r = ds.todict()
            return r
                           
        r = {}
            
        q = sess.query(Deal2).filter_by(tradeday_id=self.td.id)
        
        if threshold > 0:
            if direction == '>' :
                q = q.filter(Deal2.volume >= threshold)
            elif direction == '<':
                q = q.filter(Deal2.volume <= threshold)
        
        for i in ['b', 's', 'n']:
            deals = q.filter_by(bors = i).all()
            r[i] = count(deals)
        
        r['b-s'] = [r['b'][0] - r['s'][0],
                    r['b'][1] - r['s'][1]]
                    
        set_dealstats(self.td, threshold, direction, r)
        return r
        
def get_dadan_threshold(close_price, t=500000):
    '''根据收盘价确定大单的笔数'''
    p = close_price
    
    return int(t/1000/p) * 1000
    
if __name__ == '__main__':
    start = '2008-02-20'
    end = '2008-04-10'
    
    cs = get_stcodes()
    for c in cs[:20]:
        print c
        s = find_stock(c)
        tds = s.tds_between(start, end)
        
        if len(tds) == 0:continue
        
        for td in tds:
            a = Analyst1(td)
            if not a.has_deals():
                a.deals2db()
        
